package com.xh.core.intercept;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xh.core.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/*
 * @Author daiwei
 * @Description
 * @Date 2018/8/16 08:37
 **/
@Slf4j
public class TokenInterceptor extends HandlerInterceptorAdapter {

    private boolean isAnsynJsonRequest(HttpServletRequest request){
//        System.out.println(request.getHeader("x-requested-with"));
        if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { //如果是ajax请求响应头会有x-requested-with
            return true;
        }
        return false;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestToken=request.getHeader("REQUEST_TOKEN");
        if(StringUtils.isEmpty(requestToken)){
            if (!isAnsynJsonRequest(request)) {
                request.getSession(true).setAttribute("token", UUID.randomUUID().toString());
            }
        }else{
            if (isRepeatSubmit(request)) {
                //response.setStatus(9010); //设置状态码
                String token=(String) request.getSession(true).getAttribute("token");
                response.setHeader("REQUEST_TOKEN", token);
                response.setHeader("XH_STATUS", "requestRepeat");
                return false;
            }else{
                String newToken=UUID.randomUUID().toString();
                request.getSession(true).setAttribute("token", newToken);
                response.setHeader("REQUEST_TOKEN",newToken);
                return true;
            }
        }
        return super.preHandle(request, response, handler);
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception{
        super.afterCompletion(request,response,object,exception);
    }
    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(false).getAttribute("token");
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getHeader("REQUEST_TOKEN");
        if (StringUtils.isEmpty(clinetToken)) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }
}